package main

import (
	"flag"
	"lutai/src"
	"lutai/src/logger"
	"lutai/src/service/db"
	"os"
	"os/signal"
	"sync/atomic"
	"syscall"
)

var (
	address       = flag.String("addr", "0.0.0.0:8088", `监听的地址和端口`)
	dsn           = flag.String("mysql", "root:CqmygYsdss@0925@tcp(123.56.17.217:3389)/lutai?charset=utf8", `mysql连接串`)
	webPath       = flag.String("web", "", `静态站点目录`)
	devMode       = flag.Bool("dev", false, "开发模式")
	debug         = flag.Bool("debug", false, "开启debug模式")
	trace         = flag.Bool("trace", false, "开启trace模式")
	debugAndTrace = flag.Bool("DV", false, "开启debug和trace模式")
)

func main() {
	flag.Parse()

	if *debugAndTrace {
		*debug = true
		*trace = true
	}

	logger.Init(*debug, *trace)

	if os.Getenv("APP_ENV") == "" {
		if *devMode {
			os.Setenv("APP_ENV", "development")
		} else {
			os.Setenv("APP_ENV", "production")
		}
	}

	var state int32 = 1

	app, db := src.New(&src.Config{
		DBConfig:   &db.Config{DSN: *dsn, Trace: *trace},
		StaticPath: *webPath,
	})

	ac := make(chan error)
	sc := make(chan os.Signal, 1)

	signal.Notify(sc,
		syscall.SIGHUP,
		syscall.SIGINT,
		syscall.SIGTERM,
		syscall.SIGQUIT)

	go func() {
		ac <- app.Listen(*address)
	}()

	logger.Infof("服务启动成功[%s]", *address)

	select {
	case err := <-ac:
		if err != nil && atomic.LoadInt32(&state) == 1 {
			logger.Errorf(err.Error())
		}
	case sig := <-sc:
		atomic.StoreInt32(&state, 0)
		logger.Infof("获取到退出信号[%d]", sig)
		if err := app.Close(); err != nil {
			logger.Errorf(err.Error())
		}
	}

	db.Close()
	os.Exit(int(atomic.LoadInt32(&state)))
}
